using System;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using LitJson;
using dotnet;
using wspace;
using ssh;

namespace command
{
    public class Init : Cmd
    {
        public Init()
        {
            this.Command = "init";
            this.NeedArg = true;
            this.IsWorkAreaCmd = false;
            this.Discript = "Create a synchronous directory and link to the server.";
            this.Format = "init [user@host:dir] [-p port], the default port is 22";
            this.Function = Func;
        }

        private ServerInfo AnaParam(string[] args)
        {
            if (args.Length != 2 && args.Length != 4)
            {
                Utils.ErrorFormat(this.Format);
                return null;
            }
            if (args.Length == 4 && !args[2].Equals("-p"))
            {
                if (!(new Regex("^[0-9]+$").IsMatch(args[3])))
                {
                    Utils.ErrorFormat(this.Format);
                    return null;
                }
            }
            Match match = Regex.Match(args[1], @"^([A-Za-z][\w-]*)@([A-Za-z0-9.]+):([\w./\-\u4e00-\u9fa5]+)$");
            if (!match.Success)
            {
                Utils.ErrorFormat(this.Format);
                return null;
            }
            ServerInfo info = new ServerInfo();
            info.user = match.Result("$1");
            info.host = match.Result("$2");
            info.dir =  match.Result("$3");
            info.port = args.Length == 4 ? Convert.ToInt32(args[3]) : 22;
            return info;
        }

        private void Func(string[] args)
        {
            if (Utils.GetTopCfgPath() != null)
            {
                Utils.ErrorLog("Here is already a sync folder.");
                return;
            }
            string cfgpath = Utils.MakeCurCfgPath();
            ServerInfo sinfo = this.AnaParam(args);
            if (sinfo == null)
            {
                return;
            }

            System.Console.Write("Please entry you password:");
            sinfo.pwd = System.Console.ReadLine();
            SftpConnect brg = new SftpConnect(sinfo);
            if (!brg.Connect())
            {
                return;
            }

            try
            {
                bool isexit = brg.sftp.Exists(sinfo.dir);
                if (!isexit)
                {
                    Utils.ErrorLog("Remote directory doesn't exist.");
                    return;
                }
            }
            catch (Exception e)
            {
                Utils.ErrorLog(e.Message);
                return;
            }
            finally
            {
                brg.DisConnect();
            }

            try
            {
                Directory.CreateDirectory(cfgpath);
                FileStream filestm = File.Create(cfgpath + Utils.GetSlash() + Configs.ConfigName);
                string cfgstr = JsonMapper.ToJson(sinfo);
                filestm.Write(Encoding.UTF8.GetBytes(cfgstr));
                filestm.Close();
            }
            catch (Exception e)
            {
                System.Console.WriteLine("[Error]");
                System.Console.WriteLine("\t" + e.Message);
                return;
            }
            Utils.SuccessLog("The synchronization folder was successfully initialized.");
        }
    }
}